package com.qf.controller;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.entity.User;
import com.qf.service.UserListService;

import com.qf.util.R;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * --- 今日无事,勾栏听曲 ---
 *
 * @author JinZhiHao
 * @date 2024/12/2
 * @desc
 */

@RestController
@RequestMapping("/user")
public class UserListController {

    @Autowired
    private UserListService UserListService;

    /**
     * 模糊和分页查询用户列表
     */
    @GetMapping("/list")
    public R list(User user){

        PageHelper.startPage(user.getPageNum(),user.getPageSize());

        List<User> list = UserListService.list(user);
        System.out.println("list = " + list);

        PageInfo<User> pageInfo = new PageInfo(list);
        System.out.println("pageInfo = " + pageInfo);

        return R.ok(pageInfo);
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
    public R add(@RequestBody User user){
        UserListService.add(user);
        return R.ok();
    }

    /**
     * 根据id更改用户信息
     */
    @PostMapping("/update")
    public R update(@RequestBody User user){
        System.out.println("user ==============> " + user);
        UserListService.update(user);
        return R.ok();
    }

    /**
     * 根据id删除用户
     */
    @GetMapping("/del")
    public R del( Integer id){
        int i =  UserListService.del(id);
        if(i > 0){
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 导出excel表格
     */
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws Exception {
        User user = new User();
        List<User> list = UserListService.list(user);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("用户信息表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class).sheet("用户信息表").doWrite(list);
    }

}
